package com.coda.service.impl;

import com.coda.adminVo.fee.FeeKeyVo;
import com.coda.entity.FeeKey;
import com.coda.entity.FeeValue;
import com.coda.mapper.FeeMapper;
import com.coda.service.FeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class FeeServiceImpl implements FeeService {
    @Autowired
    private FeeMapper feeMapper;
    /**
     * 保存或更新杂费值
     * @param feeValue
     */
    @Override
    public void saveOrUpdateValue(FeeValue feeValue) {
        if (feeValue.getId() == null){
            feeMapper.insertValue(feeValue);
        }else {
            feeMapper.updateValue(feeValue);
        }
    }

    /**
     *保存或更新杂费名称
     */
    @Override
    public void saveOrUpdateKey(FeeKey feeKey) {
        if (feeKey.getId() == null){
            feeMapper.insertKey(feeKey);
        }else {
            feeMapper.updateKey(feeKey);
        }

    }

    /**
     * 查询全部杂费名称和杂费值列表
     * @return
     */
    @Override
    public List<FeeKeyVo> list() {
        //创建集合接收返回对象
        List<FeeKeyVo> feeKeyVos = new ArrayList<>();

        //获取所有feekey
        List<FeeKey> feeKeys = feeMapper.getFeeKeys();

        //遍历feekeys，获取里面的属性
        for (FeeKey feeKey : feeKeys) {
            //创建单个vo对象接收一次遍历的值
            FeeKeyVo feeKeyVo = new FeeKeyVo();
            //设置值
            feeKeyVo.setId(feeKey.getId());
            feeKeyVo.setName(feeKey.getName());

            //通过feekey的id获取feevalue
            List<FeeValue> feeValues = feeMapper.getFeeValues(feeKey.getId());
            feeKeyVo.setFeeValueList(feeValues);

            //将单个vo对象添加进vo集合
            feeKeyVos.add(feeKeyVo);
        }
        return feeKeyVos;
    }

    /**
     * 根据id删除杂费值
     * @param id
     */
    @Override
    public void deleteValueById(Long id) {
        feeMapper.deleteValueById(id);
    }

    /**
     * 根据id删除杂费名称
     * @param id
     */
    @Transactional
    @Override
    public void deleteKeyById(Long id) {
        //删除fee_key对应的信息
        feeMapper.deleteKeyById(id);

        //根据fee_key中的id删除fee_value中的信息
        feeMapper.deleteValueByKeyId(id);
    }
}
